<template>
  <div style="margin-top: 2px" >
    <a-layout>
      <top-bar @sendRoutes="sendRoutes" @sendSearchText="sendSearchText"/> <!-- 获取组件的值-->
      <a-layout-content :style="{padding: '0 26px', marginTop: '64px', minHeight: '600px'}">
        <!--筛选区-->
        <a-collapse v-if="filterVisible" :style="{padding: '0 50px', marginTop: '10px'}">
          <a-collapse-panel key="0" header="筛选" :style="{content: 'right'}">
            <!-- 类别筛选区 -->
            <a-row style="align-items: center">
              <a-col :span="6">
                <a-breadcrumb :style="{padding: '30px 50px', marginTop: '15px'}" v-if="level1Visiable">
                  <a-breadcrumb-item>
                    <!--一级菜单-->
                    {{currentLevel1.name}}
                  </a-breadcrumb-item>
                  <a-breadcrumb-item v-if="level2Visiable">
                    <!--二级菜单-->
                    <span v-if="currentLevel2!==null">{{currentLevel2.name}}</span>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item v-for="item in option_level2">
                          <a target="_blank" @click="handleLevel2(item)">{{item.name}}</a>
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-breadcrumb-item>
                  <a-breadcrumb-item v-if="level3Visiable">
                    <!--三级菜单-->
                    <span v-if="currentLevel3!==null">{{currentLevel3.name}}</span>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item v-for="item in option_level3">
                          <a target="_blank" @click="handleLevel3(item)">{{item.name}}</a>
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-breadcrumb-item>
                </a-breadcrumb>
              </a-col>
              <a-col :span="16">
                <a-tag closable @close="delTag(tag)" v-for="tag in valueTags">
                  {{tag.title}}:{{tag.value }}
                </a-tag>
              </a-col>
              <a-col :span="2">
                <a-button type="primary" v-if="submitVisible" @click="submitSelect">确定筛选</a-button>
              </a-col>
            </a-row>
            <!-- 品牌筛选 -->
            <a-row v-if="aggs.brands.length > 0" style="align-items: center">
              <a-col :span="2" style="background-color:#F1E9E9BA">
                <a-typography-title :level="5">
                  品牌: (多选 <a-checkbox v-model:checked="checkBox1MultiChecked" @change="brandsCheckBox"/>)
                </a-typography-title>
              </a-col>
              <a-col :span="22">
                <div style="background-color: #ececec; padding: 10px">
                  <a-flex gap="middle" horizontal>
                    <a-col :span="2" v-for="(brand, index) in aggs.brands" :key="index">
                      <a-card hoverable :title="brand.brandName" :bordered="false" @click="handleBrand(brand)">
                        <a-image :src="brand.brandImg" :preview="false"/>
                      </a-card>
                      <div v-if="checkBox1.visible">
                        <a-checkbox @change="brandCheckBox(brand, index)" v-model:checked="checkBox1.checked[index]"></a-checkbox>
                      </div>
                    </a-col>
                  </a-flex>
                </div>
              </a-col>
            </a-row>
            <!-- 属性筛选 -->
            <a-row v-if="aggs.attrs.length > 0" style="align-items: center; margin-top: 2px" v-for="attr in aggs.attrs">
              <a-col :span="2" style="background-color:#F1E9E9BA">
                <a-typography-title :level="5">
                  {{attr.attrName}}:
                  <a-button primary>
                    <a-typography-text>
                      多选
                    </a-typography-text>
                    <a-checkbox v-model:checked="attr.multiChecked" @change="attrsCheckBox(attr)"/>
                  </a-button>

                </a-typography-title>
              </a-col>
              <a-col :span="22">
                <div style="background-color: #ececec; padding: 10px">
                  <a-card :title="attr.attrName">
                    <a-card-grid hoverable style="width: 10%; text-align: center" v-for="(valueName,index) in attr.values" :key="index">
                      <a-typography-text strong @click="handleAttrValue(attr, valueName)" >
                        {{valueName}}
                      </a-typography-text>
                      <div v-if="typeof checkBox2.get(attr.attrId)!= 'undefined' && checkBox2.get(attr.attrId).visible">
                        <a-checkbox @change="attrCheckBox(attr, index, valueName)" v-model:checked="checkBox2.get(attr.attrId).checked[index]"></a-checkbox>
                      </div>
                    </a-card-grid>
                  </a-card>
                </div>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-row >
          <a-col :span="4">
            <a-statistic title="总商品数" :value="totalNum" style="margin-right: 50px; margin-top: 8px">
              <template #suffix>
                <BarChartOutlined />
              </template>
            </a-statistic>

          </a-col>
          <a-col :span="2">
            <a-checkbox style="margin-top: 15px" v-model:checked="hasStock">仅显示有货</a-checkbox>
          </a-col>
          <a-col :span="18">

            <div style="margin-top: 15px">
              <a-radio-group v-model:value="placement" v-if="radioGroupVisible">
                <a-radio-button @focus="focus('saleCount')" value="saleCount">
                  销量
                  <UpOutlined v-if="upVisible" @click="upDownChange('up', 'saleCount')"/>
                  <DownOutlined v-if="downVisible" @click="upDownChange('down', 'saleCount')"/>
                </a-radio-button>
                <a-radio-button @focus="focus('skuPrice')" value="skuPrice">
                  价格
                  <UpOutlined @click="upDownChange('up', 'skuPrice')" v-if="upVisible"/>
                  <DownOutlined v-if="downVisible" @click="upDownChange('down', 'skuPrice')"/>
                </a-radio-button>
                <a-radio-button @focus="focus('hotScore')" value="hotScore">
                  评分
                  <UpOutlined v-if="upVisible" @click="upDownChange('up', 'hotScore')"/>
                  <DownOutlined v-if="downVisible" @click="upDownChange('down', 'hotScore')"/>
                </a-radio-button>

                <a-popover title="区间" trigger="click" v-model:open="priceAppoverVisible">
                  <template #content>
                    <a-flex gap="middle" horizontal>
                      <a-input-number v-model:value="lowPrice" prefix="￥" style="width: 25%" />
                      ~
                      <a-input-number v-model:value="highPrice" prefix="￥" style="width: 25%" />
                      <a-button @click="skuPriceSectionSubmit">提交</a-button>
                    </a-flex>
                  </template>
                  <a-radio-button value="priceSection">价格区间</a-radio-button>
                </a-popover>
              </a-radio-group>
            </div>
          </a-col>
        </a-row>

        <!-- 商品展示块 -->
        <div id="scrollId">
          <a-row :gutter="[16, 24]">
            <a-col class="gutter-row" :span="4" v-for="product in productList">
              <a-card hoverable @click="handleProduct(product.spuId, product.skuId)">
                <template #cover>
                  <img
                      alt="商品默认图片"
                      :src="product.skuImg"
                      :fallback="imgErr"
                  />
                </template>
                <a-card-meta>  <!-- :title="product.skuTitle" :description="product.skuPrice"-->
                  <template #avatar>
                    <a-avatar :src="product.brandImg" />
                    <a-row>
                      <a-col :span="8">
                        <a-typography-title :level="5" :style="{marginTop: '4px'}">
                          ￥{{ product.skuPrice }}
                        </a-typography-title>
                        <a-typography-title :level="5" :style="{marginTop: '4px'}">
                          月销:{{product.saleCount}}
                        </a-typography-title>
                      </a-col>
                      <a-col :span="16" style="overflow: hidden">
                        <a-typography-paragraph>
                          <div style="text-overflow: ellipsis;
                            overflow: hidden;
                            display: -webkit-box;
                            -webkit-line-clamp: 3;
                            -webkit-box-orient: vertical;" v-html="product.skuTitle"/>
                        </a-typography-paragraph>
                      </a-col>
                    </a-row>
                  </template>
                  <template #actions>

                  </template>
                </a-card-meta>
              </a-card>
            </a-col>

          </a-row>

        </div>

        <!-- 检索加载状态 -->
        <a-skeleton active v-if="skeletonVisiable"  :style="{padding: '0 50px', marginTop: '64px'}"/>

        <div v-if="paginationVisible" style="margin-top: 8px">
          <a-pagination v-model:current="currentPage" show-quick-jumper :total="totalNum" @change="paginationOnChange" />
        </div>

        <!-- 搜索结果为空 -->
        <a-result title="Opps！货架上空空如也~~" v-if="emptyResultVisiable">
          <template #icon>
            <a-empty description="Empty" />
          </template>
          <template #extra>
            <router-link to="/">
              <a-button type="primary">去首页逛逛</a-button>
            </router-link>
          </template>
        </a-result>

      </a-layout-content>
      <tail-bar/>
    </a-layout>
  </div>
</template>

<script setup>
import TopBar from '@/components/common/TopBar'
import TailBar from "@/components/common/TailBar"
import {ref} from "vue";
import {onUnmounted, onMounted, watch} from "vue";
import request from "@/utils/request";
import imgErr from '@/assets/imgError.png'
import {message} from "ant-design-vue";
import {BarChartOutlined,UpOutlined, DownOutlined} from '@ant-design/icons-vue';
import router from "@/router";

    let placement = ref('');
    let lowPrice = ref(null)
    let highPrice = ref(null)

    let productList = ref([])
    let currentLevel1 = ref(null)
    let currentLevel2 = ref(null)
    let currentLevel3 = ref(null)
    let option_level2 = ref(null)
    let option_level3 = ref(null)
    //查询参数
    let searchParam = ref({
      keyword: '',
      catId: null,
      brandIds: [],
      sort: 'saleCount_DESC',
      skuPriceSection: '',
      attrs: [],
      page: 1,
      pageSize: 10
    })
    let hasStock = ref(false)

    watch(searchParam.value, (newVal, oldValue) => {
      submitVisible.value = searchParam.value.brandIds.length > 0 || searchParam.value.attrs.length > 0;
    })

    watch(hasStock, (value)=>{
      if(value){
        console.log('仅仅挑选有货')
        searchParam.value['hasStock'] = 1
      }else {
        console.log('挑选所有')
        delete searchParam.value.hasStock
      }
      postSearch(searchParam.value)
    })

    function initSearchParam(){
      searchParam.value = {
        keyword: '',
        catId: null,
        brandIds: [],
        sort: '',
        hasStock: 1,
        skuPriceSection: '',
        attrs: [],
        pageNum: 0
      }
    }

    let skeletonVisiable = ref(true)
    let emptyResultVisiable = ref(false)
    let level1Visiable = ref(false)
    let level2Visiable = ref(false)
    let level3Visiable = ref(false)
    let submitVisible = ref(false)
    let checkBox1MultiChecked = ref(false)
    let priceAppoverVisible = ref(false)
    let upVisible = ref(true)
    let downVisible = ref(false)
    let paginationVisible = ref(true)
    let radioGroupVisible = ref(false)
    let filterVisible = ref(false)

    let checkBox1 = ref({checked: [], visible: false})
    let checkBox2 = ref(new Map()) //(key: attrId, value: {visible: true/false, checked[]})

    let selectAttrValues = new Map() //(key: attrId, value: {attrId: 0, values: []}填装属性值)
    let valueTags = ref([]) // {Id, title value, type}

    //聚合参数
    let aggs = ref({
      attrs: [],
      brands: [],
      categories: []
    })

    //搜索到的商品总数
    let totalNum = ref(0)

    function sendRoutes(data){
      //接收从子组件 topBar来的 routes 值
      currentLevel1.value = data.routes[0][0]
      option_level2.value = data.routes[1]
      currentLevel2.value = data.secondItem
      option_level3.value = data.routes[2]
      currentLevel3.value = data.thirdItem
      //TODO 更新查询参数
      console.log('更新查询参数--分类查询', data)
      level1Visiable.value = true
      searchParam.value.catId = data.thirdItem.catId
      postSearch(searchParam.value)
    }

    function sendSearchText(data){
      //接收从子组件 topBar来的 searchValue 值
      //TODO 更新查询参数
      if(typeof data !== "undefined" && data !== null){
        searchParam.value.keyword = data
        searchParam.value.page = 1
        currentPage.value = 1
        searchParam.value.skuPriceSection = ''
        searchParam.value.catId = null
        placement.value = ''
        lowPrice.value = null
        highPrice.value = null
        postSearch(searchParam.value)
      }
    }

    function handleLevel2(data){
      //TODO 更新查询参数
      console.log('更新查询参数', data)
      currentLevel3.value = null
    }

    function handleLevel3(data){
      console.log(data)
      //TODO 更新查询参数
      console.log('3级-更新查询参数', data)
      currentLevel3.value = data
      searchParam.value.catId = data.catId
      postSearch(searchParam.value)
    }

    // 搜索请求
    function postSearch(data){
      skeletonVisiable.value = true
      radioGroupVisible.value = false
      filterVisible.value = false
      emptyResultVisiable.value = false
      paginationVisible.value = false
      productList.value = []
      request({
        url: '/search/es/product/sku/search',
        method: 'post',
        data: request.adornData(data, false)
      }).then( res => {
        if(res.code === 0){
          // 处理数据
          console.log("响应的参数", res)
          if(typeof res.data.total !== "undefined" && res.data.total !== null){
            totalNum.value = res.data.total
          }
          if(typeof res.data.brands !== "undefined" && res.data.brands !== null){
            aggs.value.brands = res.data.brands
          }
          if(typeof res.data.attrs !== "undefined" && res.data.attrs !== null){
            aggs.value.attrs = res.data.attrs
            //分割属性值，添加一个新数组字段`values`来存放属性值，后端传来的 attrValue='16_A13仿生:HUAWEI Kirin 970'
            aggs.value.attrs.forEach(item => {
              item['values'] = item.attrValue.split('_')[1].split(':')
            })
          }
          if(typeof res.data.categories !== "undefined" && res.data.categories !== null){
            aggs.value.categories = res.data.categories
          }
          if(res.data.products === null || typeof res.data.products === "undefined"){
            emptyResultVisiable.value = true
            paginationVisible.value = false
            //将查询参数清空
          }
          if(typeof res.data.products !== "undefined" && res.data.products.length > 0) {
            emptyResultVisiable.value = false
            paginationVisible.value = true
            radioGroupVisible.value = true
            filterVisible.value = true
            res.data.products.forEach(item => {
              productList.value.push(item)
            })
          }
          //根据搜索聚合结果，获取新的种类选项
          if(aggs.value.categories.length > 0){
            aggs.value.attrs.forEach(item => {
              item['multiChecked'] = false
            })
            let category = aggs.value.categories[0]
            request({
              url: `product/category/options/${category.catalogId}`,
              method: 'get',
            }).then((res) => {
              currentLevel1.value = res.data.level1
              option_level2 = res.data.level2
              option_level3 = res.data.level3
              level1Visiable.value = true
              level2Visiable.value = true
              level3Visiable.value = true
            }).catch(err => {
              console.log('获取分类异常', err)
              message.error("获取分类失败！"+err.message)
            })
          }
        }
      }).catch((err)=>{
        console.log('搜索异常', err)
        message.error("搜素失败！"+err.message)
        emptyResultVisiable.value = true
        paginationVisible.value = false
      }).finally(()=>{
        skeletonVisiable.value = false
        checkBox1MultiChecked.value = false
        valueTags.value = []

        //处理缓存
        searchParam.value.brandIds = []
        searchParam.value.attrs = []
        searchParam.value.sort = ''
        //searchParam.value.skuPriceSection = ''

        if(typeof checkBox1.value !== "undefined"){
          for (let i = 0; i < checkBox1.value.checked.length; i++) {
            checkBox1.value.checked[i] = false
          }
        }
        if(typeof checkBox2.value !== "undefined"){
          checkBox2.value.forEach(item => {
            item.visible = false
            for (let i = 0; i < item.checked.length; i++) {
              if(item.checked[i]){
                item.checked[i] = false
              }else {
                item.checked.splice(i,1)
              }
            }
          })
        }
        selectAttrValues.forEach(item => {
          item.values = []
        })
      })
    }

    function brandsCheckBox(){
      if(checkBox1MultiChecked.value === true){
        checkBox1.value.visible = true
      }else {
        checkBox1.value.visible = false
        //将brand参数清空
        for (let i = 0; i < checkBox1.value.checked.length; i++) {
          checkBox1.value.checked[i] = false
        }
        searchParam.value.brandIds = []
        //brand tag清空
        let collectRes = []
        for (let i = 0; i < valueTags.value.length; i++) {
          console.log('clear')
          if(valueTags.value[i].type !== 'brand'){
            collectRes.push(valueTags.value[i])
          }
        }
        valueTags.value = collectRes
      }
    }

    function attrsCheckBox(attr){
      //将 id 的attr checkBox显现
      let id = attr.attrId
      if(attr.multiChecked){
        let checked = []
        for (let i = 0; i < attr.values.length; i++) {
          checked.push(false)
        }
        checkBox2.value.set(id, {visible: true, checked: checked})
      }else {
        //清理掉里面的勾选项、selectAttrValues、请求参数
        for (let i = 0; i < checkBox2.value.get(id).checked.length; i++) {
          checkBox2.value.get(id).checked[i] = false
        }
        checkBox2.value.set(id, {visible: false, checked: checkBox2.value.get(id).checked})
        searchParam.value.attrs = []
        //清空attr atg
        let collectRes = []
        valueTags.value.forEach(item=>{
          if(item.type !== 'attr' || item.id !== attr.attrId){
            collectRes.push(item)
          }
        })
        valueTags.value = collectRes
      }
      console.log('处理后的checkbox2', checkBox2.value, selectAttrValues.get(id))
    }

    function brandCheckBox(brand, index){
      if(checkBox1.value.checked[index]){
        valueTags.value.push({id: brand.brandId, title: '品牌',value: brand.brandName, type: 'brand'})
        searchParam.value.brandIds.push(brand.brandId)
      }else {
        //取消多选，删除该brandId
        for (let i = 0; i < valueTags.value.length; i++) {
          if(valueTags.value[i].type==='brand' && valueTags.value[i].id === brand.brandId){
            valueTags.value.splice(i,1)
          }
        }
        for (let i = 0; i < searchParam.value.brandIds.length; i++) {
          if(searchParam.value.brandIds[i] === brand.brandId){
            searchParam.value.brandIds.splice(i, 1)
          }
        }
      }
    }

    function attrCheckBox(attr, index, valueName){
      if(checkBox2.value.get(attr.attrId).checked[index]){
        //该属性被选择了，需要将其添加到查询参数
        valueTags.value.push({id: attr.attrId, title: attr.attrName ,value: valueName, type: 'attr'})
        if(typeof selectAttrValues.get(attr.attrId) === "undefined"){
          let value = {attrId: attr.attrId, values: []}
          value.values.push(valueName)
          selectAttrValues.set(attr.attrId,value)
        } else {
          let temp = selectAttrValues.get(attr.attrId)
          temp.values.push(valueName)
          selectAttrValues.set(attr.attrId, temp)
        }
      } else {
        //该属性没有被选择，需要剔除 valueName
        for (let i = 0; i < valueTags.value.length; i++) {
          if(valueTags.value[i].id === attr.attrId && valueTags.value[i].value === valueName &&  valueTags.value[i].type ==='attr'){
            valueTags.value.splice(i, 1)
            break
          }
        }
        let del = selectAttrValues.get(attr.attrId).values
        for (let i = 0; i < del.length; i++) {
          if(del[i] === valueName){
            del.splice(i,1)
            break
          }
        }
        if(del.length > 0){
          selectAttrValues.set(attr.attrId, {attrId: attr.attrId, values: del})
        }else {
          selectAttrValues.delete(attr.attrId)
        }
      }
      let searchAttr = []
      selectAttrValues.forEach(item => {
        let str = ''
        if(item.values.length > 0){
          str += item.attrId+'_'
          for (let i = 0; i < item.values.length; i++) {
            str += item.values[i]
            if(i < item.values.length-1){
              str+=':'
            }
          }
        }
        if(str !== ''){
          searchAttr.push(str)
        }
      })
      searchParam.value.attrs = searchAttr
      console.log('单个attrCheckBox处理后的请求参数', searchParam.value.attrs)
    }

    function submitSelect(){
      postSearch(searchParam.value)
    }


    function upDownChange(item, event){
      if(item === 'up'){
        //原本的 up 点击了，转为 down
        upVisible.value = false
        downVisible.value = true
        console.log('降序')
      }
      if(item === 'down'){
        upVisible.value = true
        downVisible.value = false
        console.log('升序')
      }
    }

    function focus(value){
      console.log('聚焦--', value)
      let sortParam = value+'_'
      if(upVisible.value){
        sortParam += 'ASC'
      }
      if(downVisible.value){
        sortParam += 'DESC'
      }
      console.log('排序请求参数', sortParam)
      searchParam.value.sort = sortParam
      postSearch(searchParam.value)
    }

    function skuPriceSectionSubmit(){
      console.log('提交价格区间', lowPrice.value, highPrice.value)
      searchParam.value.page = 1
      currentPage.value = 1
      placement.value = ''
      if(lowPrice.value != null && highPrice.value != null){
        searchParam.value.skuPriceSection = lowPrice.value+'_'+highPrice.value
        postSearch(searchParam.value)
      }
      if(lowPrice.value != null && highPrice.value == null){
        //大于条件
        searchParam.value.skuPriceSection = lowPrice.value+'_'
        postSearch(searchParam.value)
      }
      if(lowPrice.value == null && highPrice.value != null){
        //小于条件
        searchParam.value.skuPriceSection = '_'+highPrice.value
        postSearch(searchParam.value)
      }
    }

    const delTag = (tag)=>{
      console.log('剔除单个tag', tag)
    }

    //点击单个品牌跳转
    const handleBrand = (brand)=>{
      console.log('点击了品牌', brand)
      searchParam.value.brandIds.push(brand.brandId)
      postSearch(searchParam.value);
    }

    //点击单个属性搜索
    const handleAttrValue = (attr, value) => {
      console.log('点击了属性', attr, value)
      searchParam.value.attrs.push(attr.attrId+'_'+value)
      postSearch(searchParam.value)
    }

    //分页跳转 pageSize默认为10
    let currentPage = ref(1) //当前页
    const paginationOnChange = (page, pageSize)=>{
      searchParam.value.page = page
      searchParam.value.pageSize = pageSize
      postSearch(searchParam.value)
    }

    //处理点击商品跳转到商品详情页
    const handleProduct = (spuId, skuId)=>{
      router.push({
        path: '/product/info/baseAttrs',
        query: {spuId, skuId}
      })
    }

    onUnmounted(()=>{
      //清空查询参数
      searchParam.value.brandIds = []
      searchParam.value.attrs = []
      searchParam.value.sort = ''
      searchParam.value.skuPriceSection = ''
      searchParam.value.pageNum = 0
    })

</script>

<style>

</style>